package com.pzr.demo.web.controller.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.junit.Test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.hgx.db.DbBase;
import com.hgx.db.HC3P0ConnentionProvider;
import com.hgx.entity.AjaxResult;
import com.hgx.entity.MyProcessDefinition;
import com.hgx.entity.TestProcessEntity;
import com.hgx.entity.TestUser;

/**
 * 流程测试
 * 
 * @author hgx
 * 
 */
@Controller
@RequestMapping("/test/process.do")
public class ProcessTestController extends BaseController {

	private TestProcessEntity tpe = new TestProcessEntity();// 流程对象(测试用)

	/**
	 * 流程部署
	 * 
	 * @return
	 */
	@RequestMapping(params = "method=deploy")
	@ResponseBody
	public String processDeployAction() {
		System.out.println("访问成功!-------------------------");
		// 流程部署服务
		RepositoryService repositoryService = super.getRepositoryService();
		Deployment deployment = repositoryService.createDeployment().name(tpe.getProcessName()).addClasspathResource(tpe.getProcessResourePath()).deploy();
		System.out.println("部署ID：" + deployment.getId());// 1
		System.out.println("部署时间：" + deployment.getDeploymentTime());
		return super.getSuccessJsonStr("部署成功!");
	}

	/**
	 * 
	 * 查询流程定义列表(最新版本)
	 * 
	 * @return
	 */
	// @RequestMapping(params = "method=lastVersionlist")

	@RequestMapping(params = "method=lastVersionlist", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String findLastVersionProcessDefinitionAction(HttpServletRequest request, HttpServletResponse response) {

		RepositoryService repositoryService = super.getRepositoryService();
		List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().orderByProcessDefinitionVersion().asc().list();// 使用流程定义的版本升序排列

		/*
		 * Map<String,ProcessDefinition> map集合的key:流程定义的key map集合的value:流程定义的对象
		 * 特点：当map集合key值相同的情况下，后一次的值将替换前一次的值
		 */
		Map<String, ProcessDefinition> map = new LinkedHashMap<String, ProcessDefinition>();
		if (list != null && list.size() > 0) {
			for (ProcessDefinition pd : list) {
				map.put(pd.getKey(), pd);
			}
		}
		list.clear();
		list = new ArrayList<ProcessDefinition>(map.values());
		List<MyProcessDefinition> instanceList = MyProcessDefinition.getInstanceList(list);// 自定义ProcessDefinition
																							// (原对象不能转json)
		AjaxResult ajaxResult = new AjaxResult(Status.SUCCESS.toString());
		ajaxResult.setData(instanceList);
		String jsonStr = super.getJsonStr(ajaxResult);// 转为json串

		return jsonStr;
	}

	/**
	 * 查询流程版本
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "method=findProcessDefinitionVersionAll", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String findProcessDefinitionVersionAllAction(HttpServletRequest request, HttpServletResponse response) {
		String key = request.getParameter("key");
		System.out.println("key:" + key);
		RepositoryService repositoryService = super.getRepositoryService();
		List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().processDefinitionKey(key).orderByProcessDefinitionVersion().asc().list();// 使用流程定义的版本升序排列

		List<MyProcessDefinition> instanceList = MyProcessDefinition.getInstanceList(list);// 自定义ProcessDefinition
																							// (原对象不能转json)
		AjaxResult ajaxResult = new AjaxResult(Status.SUCCESS.toString());
		ajaxResult.setData(instanceList);
		String jsonStr = super.getJsonStr(ajaxResult);// 转为json串
		return jsonStr;
	}

	/**
	 * 查询用户数据
	 * 
	 * @return
	 */
	@RequestMapping(params = "method=findTestUser", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String findTestUserAction() {
		System.out.println("-------------------------------------");
		List<TestUser> list = new ArrayList<TestUser>();

		String sql = "select id,username,sex,age,status from testUser ";
		try {

			Connection conn = HC3P0ConnentionProvider.getConnection();
			System.out.println(conn);
			PreparedStatement ps = conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				TestUser testUser = new TestUser();
				testUser.setId(rs.getString(1));
				testUser.setName(rs.getString(2));
				testUser.setSex(rs.getString(3));
				testUser.setAge(rs.getString(4));
				testUser.setStatus(rs.getString(5));
				list.add(testUser);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		AjaxResult ajaxResult = new AjaxResult(Status.SUCCESS.toString());
		ajaxResult.setData(list);
		return super.getJsonStr(ajaxResult);
	}

	/**
	 * 启动流程
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "method=processStart", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String processStartAction(HttpServletRequest request, HttpServletResponse response) {
		String key = request.getParameter("key");// 流程key
		String businessId = request.getParameter("businessId");// 业务数据主键
		String user = "张三";// 流程启动用户
		Map<String, Object> vars = new HashMap<String, Object>();
		vars.put("user", user);
		RuntimeService runtimeService = super.getRuntimeService();
		ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(key, businessId, vars);// 启动流程
		System.out.println("流程实例ID:" + processInstance.getId());
		
		DbBase db = new DbBase();
		String sqlstr = "update testuser set `status`='1' where id='"+businessId+"'";
		if(!db.executeUpdate(sqlstr)){
			System.out.println("数据同步失败!");
		}
		
		AjaxResult ajaxResult = new AjaxResult(Status.SUCCESS.toString());
		ajaxResult.setText("流程启动完成!");
		return super.getJsonStr(ajaxResult);
	}

	/**
	 * 查询流程执行至节点
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "method=findProcessHistoric", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String findProcessHistoricAction(HttpServletRequest request, HttpServletResponse response) {
		String businessId = request.getParameter("businessId");// 业务数据主键
		RuntimeService runtimeService = super.getRuntimeService();
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(businessId).singleResult();
		AjaxResult ajaxResult = new AjaxResult(Status.WARN.toString());
		if (null == processInstance) {
			ajaxResult.setWarnMessage("未找到流程!");
			return super.getJsonStr(ajaxResult);
		}
		List<HistoricActivityInstance> list = super.getHistoryService().createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).finished().list();

		ajaxResult.setStatus(Status.SUCCESS.toString());

		ajaxResult.setData(list);

		return super.getJsonStr(ajaxResult);
	}
	
	/**
	 * 查找流程下一个状态名称
	 * 
	 */
	private String findProcessStatusNextAcivitiName(String processInstanceId){
		HistoryService historyService = super.getHistoryService();
		HistoricActivityInstance hai = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).unfinished().singleResult();
		if(hai!=null){
			return hai.getActivityName();
		}else{
			return "完结";// 流程状态
		}
	}
	
}
